package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.converter.AIReadConverter;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationDO;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationOptionDO;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationOptionMapper;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.UserVocAISituationDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.UserVocAISituationCommand;
import com.cskaoyan.wordmemorize.request.UserVocAISituationOptionCommand;
import com.cskaoyan.wordmemorize.service.AIReadService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AIReadServiceImpl implements AIReadService {

    @Autowired
    AIReadConverter aiReadConverter;

    @Autowired
    UserVocAISituationMapper situationMapper;

    @Autowired
    UserVocAISituationOptionMapper optionMapper;

    /**
     * 添加AI阅读场景以及选项信息(后台等级特权管理-AI阅读)
     * @param command
     */
    @Override
    @OperateLog(dataType = "AI场景", operateType = 1, description = "新增AI场景")
    public void addAISituation(UserVocAISituationCommand command) {

// 参数校验
        if (command == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(command.getName())) {
            throw new IllegalArgumentException("场景名称不能为空");
        }

        // 检查场景名称是否已存在
        LambdaQueryWrapper<UserVocAISituationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserVocAISituationDO::getName, command.getName());
        if (situationMapper.selectCount(queryWrapper) > 0) {
            throw new IllegalArgumentException("该场景名称已存在");
        }

        // 转换并保存场景信息
        UserVocAISituationDO situationDO = aiReadConverter.userVocAISituationCommandToDO(command);
        situationMapper.insert(situationDO);

        // 保存选项信息
        if (CollectionUtils.isNotEmpty(command.getOptions())) {
            for (UserVocAISituationOptionCommand option : command.getOptions()) {
                UserVocAISituationOptionDO optionDO = aiReadConverter.userVocAISituationOptionCommandToDO(option);
                optionDO.setSituationId(situationDO.getId());
                optionMapper.insert(optionDO);
            }
        }
    }

    /**
     * 更新AI阅读场景以及选项信息(后台等级特权管理-AI阅读)
     * @param command
     */
    @Override
    @OperateLog(dataType = "AI场景", operateType = 4, description = "修改AI场景")
    public void updateAISituation(UserVocAISituationCommand command) {

        // 参数校验
        if (command == null || command.getId() == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(command.getName())) {
            throw new IllegalArgumentException("场景名称不能为空");
        }

        // 检查场景是否存在
        UserVocAISituationDO existingSituation = situationMapper.selectById(command.getId());
        if (existingSituation == null) {
            throw new IllegalArgumentException("场景不存在");
        }

        // 检查场景名称是否已存在（排除自身）
        LambdaQueryWrapper<UserVocAISituationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserVocAISituationDO::getName, command.getName())
                .ne(UserVocAISituationDO::getId, command.getId());
        if (situationMapper.selectCount(queryWrapper) > 0) {
            throw new IllegalArgumentException("该场景名称已存在");
        }

        // 更新场景信息
        UserVocAISituationDO situationDO = aiReadConverter.userVocAISituationCommandToDO(command);
        situationMapper.updateById(situationDO);

        // 先删除原有选项
        LambdaQueryWrapper<UserVocAISituationOptionDO> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(UserVocAISituationOptionDO::getSituationId, command.getId());
        optionMapper.delete(deleteWrapper);

        // 保存新选项信息
        if (CollectionUtils.isNotEmpty(command.getOptions())) {
            for (UserVocAISituationOptionCommand option : command.getOptions()) {
                UserVocAISituationOptionDO optionDO = aiReadConverter.userVocAISituationOptionCommandToDO(option);
                optionDO.setSituationId(Long.valueOf(command.getId()));
                optionMapper.insert(optionDO);
            }
        }
    }

    /**
     * 删除AI阅读场景(后台等级特权管理-AI阅读)
     * @param id
     */
    @Override
    @OperateLog(dataType = "AI场景", operateType = 2, description = "删除AI场景", logReturnValue = true)
    public void deleteAISituation(Long id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("场景ID不能为空");
        }

        // 检查场景是否存在
        if (situationMapper.selectById(id) == null) {
            throw new IllegalArgumentException("场景不存在");
        }

        // 先删除关联的选项
        LambdaQueryWrapper<UserVocAISituationOptionDO> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(UserVocAISituationOptionDO::getSituationId, id);
        optionMapper.delete(deleteWrapper);

        // 删除场景
        situationMapper.deleteById(id);

    }

    /**
     * 删除AI阅读场景中的某个选项(后台等级特权管理-AI阅读)
     * @param id
     */
    @Override
    @OperateLog(dataType = "AI场景", operateType = 2, description = "删除AI场景选项", logReturnValue = true)
    public void deleteAISituationOption(Long id) {

        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("选项ID不能为空");
        }

        // 检查选项是否存在
        if (optionMapper.selectById(id) == null) {
            throw new IllegalArgumentException("选项不存在");
        }

        // 删除选项
        optionMapper.deleteById(id);
    }

    /**
     * 批量删除AI阅读场景中的选项(后台等级特权管理-AI阅读)
     * @param ids
     */
    @Override
    @OperateLog(dataType = "AI场景", operateType = 3, description = "批量删除AI场景选项", logReturnValue = true)
    public void batchDeleteAISituationOption(List<Long> ids) {

        // 参数校验
        if (CollectionUtils.isEmpty(ids)) {
            throw new IllegalArgumentException("请选择要删除的选项");
        }

        // 批量删除
        situationMapper.deleteBatchIds(ids);
    }

    /**
     * 分页查询AI阅读场景信息(后台等级特权管理-AI阅读)
     * @param pageRequest
     * @return
     */
    @Override
    public PageDTO<UserVocAISituationDTO> getAISituationList(PageRequest pageRequest) {
        // 构建分页查询
        Page<UserVocAISituationDO> page = new Page<>(pageRequest.getPageNum(), pageRequest.getCount());

        // 执行查询
        Page<UserVocAISituationDO> result = situationMapper.selectPage(page, null);

        // 查询每个场景的选项
        List<UserVocAISituationDO> situations = result.getRecords();
        if (CollectionUtils.isNotEmpty(situations)) {
            List<Long> situationIds = situations.stream().map(UserVocAISituationDO::getId).collect(Collectors.toList());

            // 批量查询所有选项
            LambdaQueryWrapper<UserVocAISituationOptionDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(UserVocAISituationOptionDO::getSituationId, situationIds);
            List<UserVocAISituationOptionDO> options = optionMapper.selectList(queryWrapper);

            // 按场景ID分组
            Map<Long, List<UserVocAISituationOptionDO>> optionsMap = options.stream()
                    .collect(Collectors.groupingBy(UserVocAISituationOptionDO::getSituationId));

            // 设置选项到场景
            situations.forEach(situation -> {
                List<UserVocAISituationOptionDO> situationOptions = optionsMap.getOrDefault(situation.getId(), Collections.emptyList());
                situation.setOptions(situationOptions);
            });
        }

        // 转换为DTO并返回
        return aiReadConverter.toUserVocAISituationPage(result.getRecords(), result.getTotal());
    }

}